from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time


def get_driver():
    # 指定Firefox的路径，例如在Windows上：
    firefox_path = "/opt/apps/org.mozilla.firefox-nal/files/firefox-nal/firefox"

    # 使用Service来设置路径
    # service = Service(executable_path="./geckodriver", firefox_binary=firefox_path)

    opt = Options()
    opt.binary_location = firefox_path

    sv = Service("./geckodriver", log_output="./review.log")
    # 设置浏览器驱动（需要下载对应浏览器的驱动）
    driver = webdriver.Firefox(service=sv, options=opt)  # 或 Firefox(), Edge() 等

    # 打开登录页面
    driver.get("http://oa.yuxi.cn/OA/LEAP/Login/5304/BOA/Login.html?lid=35FGfBeM")

    # 找到用户名和密码输入框并输入信息
    username = driver.find_element(By.ID, "txt_flag")  # 或 By.ID, By.XPATH等
    password = driver.find_element(By.ID, "txt_pwd")

    username.send_keys("fgwzp1")
    password.send_keys("Sep91700")

    # 提交表单（找到登录按钮并点击）
    login_button = driver.find_element(By.ID, "btn_login")
    login_button.click()

    # 等待登录完成
    time.sleep(2)

    return driver


class DocReviewer:
    def __init__(self):
        self.driver = get_driver()
        pass

    def __del__(self):
        self.driver.quit()
        print("关闭浏览器")

    def start(self, count=10):
        print(f"处理{count}个文档。开始……")
        for i in range(count):
            self.review_next()

        print("完成")

    def review_next(self):
        dai_ban_gong_wen = self.driver.find_element(
            By.CSS_SELECTOR, "[ut=gwcllist_body]"
        )

        # 找到第一个待办公文
        doc = dai_ban_gong_wen.find_element(By.TAG_NAME, "a")

        self.open_review(doc)

    def open_review(self, doc):
        doc.click()

        all_windows = self.driver.window_handles
        self.driver.switch_to.window(all_windows[-1])

        new_url = self.driver.current_url
        print("新标签页网址", new_url)

        WebDriverWait(self.driver, 10).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, "[ut=tijiao]"))
        )

        bao_cun = self.driver.find_element(By.CSS_SELECTOR, "[ut=tijiao]")

        WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable(bao_cun))

        bao_cun.click()

        self.driver.switch_to.window(all_windows[0])
        # 回到首页等3秒，已读的会消失，再点开下一个公文
        time.sleep(3)


def main():
    doc_reviewer = DocReviewer()
    doc_reviewer.start(300)


if __name__ == "__main__":
    main()
